package com.huat.controller;

import com.huat.mapper.UserMapper;
import com.huat.mapper.UserMsgMapper;
import com.huat.pojo.User;
import com.huat.pojo.UserMsg;
import com.huat.service.Impl.UserServiceImpl;
import com.huat.service.UserMsgService;
import com.huat.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;

//@RestController
@Controller
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    UserMapper userMapper;
    @Autowired
    UserMsgMapper userMsgMapper;

    @RequestMapping("/user/login")
    public String login(@RequestParam("email") String email, @RequestParam("password") String passWord, Model model, HttpSession session, User user) {
        if (userService.login(email, passWord)) {
            System.out.println(passWord);
            User user1 = userMapper.findUser(email);
            UserMsg userMsg = userMsgMapper.findUserMsg(email);
            session.setAttribute("username", user1.getUserName());
            session.setAttribute("email", user1.getEmail());
            if(userMsg!=null){
                System.out.println(userMsg.getRole());
                if(userMsg.getRole().trim().equals("root")){
                    return "redirect:/houtai";
                }
                session.setAttribute("userid",userMsg.getUserId());
                return "redirect:/index.html";
            }else {
                return "redirect:/info.html";
            }
        } else {
            model.addAttribute("msg", "用户名或者密码错误！");
            return "login";
        }
    }


    @RequestMapping("/user/register")
    public String register(User user, @RequestParam("username") String username, @RequestParam("password") String password, @RequestParam("email") String email) {
//        业务层编写完毕后使用下方的方法
        user.setUserName(username);
        user.setPassword(password);
        user.setEmail(email);
        userService.register(user);
        return "redirect:/login.html";
    }

    @RequestMapping("/toLogin")
    public String toLogin() {
        return "redirect:/login.html";
    }
}
